package com.doubao.wechat.controller;

import com.doubao.common.result.Result;
import com.doubao.wechat.dto.response.OAuthTokenResponse;
import com.doubao.wechat.dto.response.OAuthUserInfo;
import com.doubao.wechat.service.OAuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 微信授权控制器
 */
@RestController
@RequestMapping("/wechat/v1")
@RequiredArgsConstructor
@Tag(name = "微信授权", description = "微信OAuth授权相关接口")
@Slf4j
public class OAuthController {

    private final OAuthService oauthService;

    @GetMapping("/authorize")
    @Operation(summary = "生成授权URL", description = "获取微信OAuth授权页面URL")
    public Result<String> authorize() {
        String authUrl = oauthService.generateAuthorizationUrl();
        return Result.success(authUrl);
    }

    @GetMapping("/callback")
    @Operation(summary = "OAuth回调", description = "处理微信OAuth授权回调")
    public Result<OAuthTokenResponse> callback(
            @RequestParam String code,
            @RequestParam(required = false) String state) {
        log.info("收到微信授权回调，code: {}, state: {}", code, state);
        return oauthService.getAccessToken(code);
    }

    @GetMapping("/user-info")
    @Operation(summary = "获取用户信息", description = "使用微信访问令牌获取用户信息")
    public Result<OAuthUserInfo> getUserInfo(@RequestParam String accessToken) {
        return oauthService.getUserInfo(accessToken);
    }

    @PostMapping("/refresh")
    @Operation(summary = "刷新令牌", description = "使用微信刷新令牌获取新的访问令牌")
    public Result<OAuthTokenResponse> refreshToken(@RequestParam String refreshToken) {
        return oauthService.refreshToken(refreshToken);
    }
}